/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Dao;

import Model.LoginModel;
import Utils.HibernateUtil;
import java.util.List;
import org.hibernate.*;

/**
 *
 * @author Thiago
 */
public class LoginDaoImp implements LoginDao {

    /**
     * @description Salva um login
     * @param login (objeto login)
     * @return
     * @author Thiago Cezar Silverio
     */
    public void save(LoginModel login) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.save(login);
            session.getTransaction().commit();
        } catch (Exception ex) {
            String erro = ex.getMessage();
        }
    }
    
    /**
     * @description remove um login
     * @param login (objeto login)
     * @return
     * @author Thiago Cezar Silverio
     */
    public void remove(LoginModel login) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.delete(login);
        session.getTransaction().commit();
    }

    /**
     * @description altera um login
     * @param login (objeto login)
     * @return
     * @author Thiago Cezar Silverio
     */
    public void update(LoginModel login) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.update(login);
        session.getTransaction().commit();
    }

    /**
     * @description busca um pessoa
     * @param id (identificador de pessoa)
     * @return PessoaModel (objeto pessoa)
     * @author Thiago Cezar Silverio
     */
    public LoginModel getLogin(int id) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            return (LoginModel) session.load(LoginModel.class, id);
        } catch (Exception e) {
            LoginModel erro =  new LoginModel();
            erro.setLogin(e.getMessage());
            return erro;
        }
    }

    
    public LoginModel getLogin(String nome, String senha) {
        LoginModel login = new LoginModel();
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        //List query = session.createQuery("SELECT idpessoa FROM login l WHERE l.login = :login AND l.senha = :senha ").setParameter("login", nome).setParameter("senha", senha).list(); 
        List query = session.createSQLQuery("select idpessoa from login log where log.login = :login").setParameter("login", nome).list();
        
        // obtém as pessoas contidos no Vector
        for (int i = 0; i < query.size(); i++) {
            String valor = query.get(i).toString();
            login = getLogin(Integer.parseInt(valor));
        }
        return login;
    }
}

